//
//  AllTrainViewController.m
//  Four_Fit_New
//
//  Created by xalo on 16/7/20.
//  Copyright © 2016年 xmaz. All rights reserved.
//

#import "AllTrainViewController.h"
#import "TrainViewController.h"
#import "ScreenModel.h"
#import "TrainListModel.h"
#import "TrainListCell.h"
#import "NewView.h"

#define kURL @"http://bea.sportq.com/SFitWeb/sfit/getSelPlan?form.device=&form.flg=0&form.mySex=0&form.phoneType=1&form.sex=0&form.sign=F5DA09199F4F5111FAE1EED4ADAC5C37&form.userId=93118&form.version=1.1.5"
#define kUpdateUrl @"http://bea.sportq.com/SFitWeb/sfit/getSelPlan?form.apparatus=%@&form.device=&form.dfficultyLevel=%@&form.flg=1&form.mySex=0&form.part=%@&form.phoneType=1&form.sex=0&form.sign=F5DA09199F4F5111FAE1EED4ADAC5C37&form.userId=93118&form.version=1.1.5"

@interface AllTrainViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    BOOL coverViewIsShow;
    NSInteger currentCount; //当前选择的那么分区
    BOOL isUpdate;
    NSInteger partIndex;
    NSInteger armedIndex;
    NSInteger levelIndex;
    
}
@property (weak, nonatomic) IBOutlet UITableView *tableView; // 展示数据
@property(nonatomic,strong) UITableView *headerTableView; //展示选择列表的
@property(nonatomic,strong)UIView *coverView; //选择列表弹出的的盖视图
//部位分区
@property (weak, nonatomic) IBOutlet UILabel *partLabel;
@property (weak, nonatomic) IBOutlet UIView *partView;
@property (weak, nonatomic) IBOutlet UIButton *partButton;
//器械分区
@property (weak, nonatomic) IBOutlet UILabel *armedLabel;
@property (weak, nonatomic) IBOutlet UIView *armedView;
@property (weak, nonatomic) IBOutlet UIButton *armedButton;
//难度分区
@property (weak, nonatomic) IBOutlet UILabel *levelLabel;
@property (weak, nonatomic) IBOutlet UIView *levelView;
@property (weak, nonatomic) IBOutlet UIButton *levelButton;

@property(nonatomic,strong)NSMutableArray *listDataSource;//选择列表的数据
@property(nonatomic,strong)NSArray *viewArray; //用来存储选择点击旋转的View

@property(nonatomic,strong)NSMutableArray *apparatusArray; //存放 器材筛选model 的数组
@property(nonatomic,strong)NSMutableArray *LevelArray; //筛选等级model
@property(nonatomic,strong)NSMutableArray *partArray; //筛选 部位model

@property(nonatomic,strong)NSMutableArray *dataSource;//展示数据的数组

@property(nonatomic,strong)NewView *mNewV;

@end

@implementation AllTrainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    currentCount = -1;
    partIndex = 0;
    armedIndex = 0;
    levelIndex = 0;
    self.navigationItem.title = @"全部课程";
    [self.partView.layer addSublayer:[self yourlittleMark]];
    [self.armedView.layer addSublayer:[self yourlittleMark]];
    [self.levelView.layer addSublayer:[self yourlittleMark]];
    self.viewArray = @[self.partView,self.armedView,self.levelView];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor colorWithRed:0.93 green:0.93 blue:0.93 alpha:1.00];
    [self.tableView registerNib:[UINib nibWithNibName:@"TrainListCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"TrainList_Cell"];
    [self.headerTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [self loadData];
}
- (void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBarHidden = NO;
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0.27 green:0.29 blue:0.33 alpha:1.00];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//获取数据
- (void)loadData{
    [[QZRequestManager sharedManager] fetchDataWithUrl:kURL parameters:nil method:@"GET" needToCaches:YES fetchData:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        for (NSDictionary *dic1 in dic[@"entRet"][@"lstApparatus"]) {
            ScreenModel *model = [[ScreenModel alloc] init];
            [model setValuesForKeysWithDictionary:dic1];
            [self.apparatusArray addObject:model];
        }
        for (NSDictionary *dic1 in dic[@"entRet"][@"lstDifficultyLevel"]) {
            ScreenModel *model = [[ScreenModel alloc] init];
            [model setValuesForKeysWithDictionary:dic1];
            [self.LevelArray addObject:model];
        }
        for (NSDictionary *dic1 in dic[@"entRet"][@"lstPart"]) {
            ScreenModel *model = [[ScreenModel alloc] init];
            [model setValuesForKeysWithDictionary:dic1];
            [self.partArray addObject:model];
        }
        for (NSDictionary *dic1 in dic[@"entRet"][@"lstTraint"]) {
            TrainListModel *model = [[TrainListModel alloc] init];
            [model setValuesForKeysWithDictionary:dic1];
            if ([model.type isEqualToString:@"0"]) {
                [self.dataSource addObject:model];
            }
        }
    } updateUI:^{
        [self.headerTableView reloadData];
        [self.tableView reloadData];
    }];
}

#pragma mark 属性懒加载
- (UIView *)coverView{
    if (!_coverView) {
        _coverView = [[UIView alloc] initWithFrame:CGRectMake(0, 31, kWidth, kHeight - 30)];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight - 30)];
        view.backgroundColor = [UIColor clearColor];
        [_coverView addSubview:view];
        [view addGestureRecognizer:tap];
        [_coverView addSubview:self.headerTableView];
    }
    return _coverView;
}
- (UITableView *)headerTableView{
    if (!_headerTableView) {
        _headerTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 0)];
        _headerTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLineEtched;
        _headerTableView.delegate = self;
        _headerTableView.dataSource = self;
    }
    return _headerTableView;
}
- (NSMutableArray *)listDataSource{
    if (!_listDataSource) {
        _listDataSource = [NSMutableArray array];
    }
    return _listDataSource;
}
- (NSMutableArray *)apparatusArray{
    if (!_apparatusArray) {
        _apparatusArray = [NSMutableArray array];
    }
    return _apparatusArray;
}
- (NSMutableArray *)LevelArray{
    if (!_LevelArray) {
        _LevelArray = [NSMutableArray array];
    }
    return _LevelArray;
}
- (NSMutableArray *)partArray{
    if (!_partArray) {
        _partArray = [NSMutableArray array];
    }
    return _partArray;
}
- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}
#pragma mark 私有方法
//显示盖视图
- (void)showCoverViewWithCellCount:(NSInteger)count{
    currentCount = count;
    NSInteger i = 0;
    if (count == 2) {
        i = 2;
    }
    else{
        i = 5;
    }
    //遍历View的数组 让点击的旋转
    for (int i = 1; i <= 3; i++) {
        UIView *view = self.viewArray[i - 1];
        if (i == currentCount) {
            [UIView animateWithDuration:0.2 animations:^{
                view.transform = CGAffineTransformMakeRotation(M_PI);
            }];
        }else{
            [UIView animateWithDuration:0.2 animations:^{
                view.transform = CGAffineTransformMakeRotation(0);
            }];
        }
    }
    if (![self.view.subviews containsObject:self.coverView]) {
        [self.view addSubview:self.coverView];
        self.coverView.backgroundColor = [UIColor colorWithRed:0.27 green:0.29 blue:0.33 alpha:0.2];
    }
    [UIView animateWithDuration:0.3 animations:^{
        self.headerTableView.frame = CGRectMake(0, 0, kWidth, 21 * i );
    }];
    coverViewIsShow = YES;
}
//隐藏
- (void)hiddenCoverViewWithCellCount:(NSInteger)count{
    if (currentCount != count) {
        currentCount = count;
        NSInteger i = 0;
        if (count == 2) {
            i = 2;
        }
        else{
            i = 5;
        }
        //遍历View的数组 让点击的旋转
        for (int i = 1; i <= 3; i++) {
            UIView *view = self.viewArray[i - 1];
            if (i == currentCount) {
                [UIView animateWithDuration:0.2 animations:^{
                    view.transform = CGAffineTransformMakeRotation(M_PI);
                }];
            }else{
                [UIView animateWithDuration:0.2 animations:^{
                    view.transform = CGAffineTransformMakeRotation(0);
                }];
            }
        }
        [UIView animateWithDuration:0.3 animations:^{
            self.headerTableView.frame = CGRectMake(0, 0, kWidth, 21 * i );
        }];
        return;
    }
        //让向上的view向下
        UIView *view = self.viewArray[count - 1];
    [UIView animateWithDuration:0.2 animations:^{
        view.transform = CGAffineTransformMakeRotation(0);
    }];
    
    [UIView animateWithDuration:0.3 animations:^{
        self.headerTableView.frame = CGRectMake(0, 0, kWidth, 0);
    }];
    self.coverView.backgroundColor = [UIColor clearColor];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
         [self.coverView removeFromSuperview];
        
    });
    coverViewIsShow = NO;
}
//选择列表出来后 点击空白页面 使界面隐藏
- (void)tapAction{
    [self hiddenCoverViewWithCellCount:currentCount];
}
//指向下的三角标志
- (CAShapeLayer *)yourlittleMark{
    CAShapeLayer *shape = [CAShapeLayer layer];
    UIBezierPath *path = [[UIBezierPath alloc] init];
    [path moveToPoint:CGPointMake(1, 3.2)];
    [path addLineToPoint:CGPointMake(5,7.5)];
    [path addLineToPoint:CGPointMake(9, 3.2)];
    shape.path = path.CGPath;
    shape.lineWidth = 1.5;
    shape.strokeColor = [UIColor colorWithRed:0.68 green:0.68 blue:0.68 alpha:1.00].CGColor;
    shape.fillColor = [UIColor clearColor].CGColor;
    return shape;
}

#pragma some button action
//部位按钮
- (IBAction)partButtonAction:(UIButton *)sender {
    if (coverViewIsShow) {
        [self hiddenCoverViewWithCellCount:1];
    }else{
        [self showCoverViewWithCellCount:1];
    }
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.headerTableView reloadData];
    });
}
//器械按钮
- (IBAction)armedButtonAction:(UIButton *)sender {
    if (coverViewIsShow) {
        [self hiddenCoverViewWithCellCount:2];
    }else{
        [self showCoverViewWithCellCount:2];
    }
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.headerTableView reloadData];
    });
}
//难度按钮
- (IBAction)levelButtonAction:(UIButton *)sender {
    if (coverViewIsShow) {
        [self hiddenCoverViewWithCellCount:3];
    }else{
        [self showCoverViewWithCellCount:3];
    }
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.headerTableView reloadData];
    });
}

#pragma mark tableView delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == self.headerTableView) {
        if (currentCount == 1) {//第一个按钮
            return self.partArray.count;
        }else if(currentCount == 2){//第二个按钮
            return self.apparatusArray.count;
        }else if (currentCount == 3){//第三个按钮
            return self.LevelArray.count;
        }
    }
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //如果是headerTableView
    if (tableView == self.headerTableView) {
        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
        //字体
        cell.textLabel.font = [UIFont systemFontOfSize:11];
        //点击第一个按钮
        if (currentCount == 1) {
            cell.textLabel.text = [self.partArray[indexPath.row] name];
            //如果当前下表是选中cell的下标 让他变色
            if (partIndex == indexPath.row) {
                cell.textLabel.textColor = [UIColor colorWithRed:1.00 green:0.76 blue:0.24 alpha:1.00];
            }
            else{
                cell.textLabel.textColor = [UIColor colorWithRed:0.60 green:0.60 blue:0.60 alpha:1.00];
            }
        }else if (currentCount == 2){ //第二个按钮
            cell.textLabel.text = [self.apparatusArray[indexPath.row] name];
            if (armedIndex == indexPath.row) {
                cell.textLabel.textColor = [UIColor colorWithRed:1.00 green:0.76 blue:0.24 alpha:1.00];
            }
            else{
                cell.textLabel.textColor = [UIColor colorWithRed:0.60 green:0.60 blue:0.60 alpha:1.00];
            }
        }else if(currentCount == 3){ //第三个按钮
            cell.textLabel.text = [self.LevelArray[indexPath.row] name];
            if (levelIndex == indexPath.row) {
                cell.textLabel.textColor = [UIColor colorWithRed:1.00 green:0.76 blue:0.24 alpha:1.00];
            }
            else{
                cell.textLabel.textColor = [UIColor colorWithRed:0.60 green:0.60 blue:0.60 alpha:1.00];
            }
        }
        return cell;
    }else{
        //主展示页面的Cell
        TrainListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TrainList_Cell" forIndexPath:indexPath];
        [cell setCellWithModel:self.dataSource[indexPath.row]];
        if (!isUpdate) {
            if (indexPath.row < 3) {
                [cell addSubview:[[NewView alloc] initWithFrame:CGRectMake(kWidth - (cell.height / 2.6), 0, cell.height / 2.6, cell.height / 2.6)]];
            }
            else{
                for (UIView *view in cell.subviews) {
                    if ([view isKindOfClass:[NewView class]]) {
                        [view removeFromSuperview];
                    }
                }
            }
        }
        else{
            for (UIView *view in cell.subviews) {
                if ([view isKindOfClass:[NewView class]]) {
                    [view removeFromSuperview];
                }
            }
        }
        return cell;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == self.headerTableView) {
        return 21;
    }
    return kHeight / 5.8;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == self.headerTableView) {
        if (self.dataSource.count) {
            [self.dataSource removeAllObjects];
        }
        switch (currentCount) {
            case 1:
                partIndex = indexPath.row;
                self.partLabel.text = [NSString stringWithFormat:@"部位：%@", [[self.partArray[indexPath.row] name] componentsSeparatedByString:@"("].firstObject];
                break;
            case 2:
                armedIndex = indexPath.row;
                self.armedLabel.text = [NSString stringWithFormat:@"器械：%@",[self.apparatusArray [indexPath.row] name]];
                break;
            case 3:
                levelIndex = indexPath.row;
                self.levelLabel.text = [NSString stringWithFormat:@"难度：%@",[self.LevelArray[indexPath.row] name]];
                break;
            default:
                break;
        }
        [self hiddenCoverViewWithCellCount:currentCount];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.headerTableView reloadData];
        });
        ScreenModel *model1 = self.apparatusArray[armedIndex];
        ScreenModel *model2 = self.LevelArray[levelIndex];
        ScreenModel *model3 = self.partArray[partIndex];
        [[QZRequestManager sharedManager] fetchDataWithUrl:[NSString stringWithFormat:kUpdateUrl,model1.code,model2.code,model3.code] parameters:nil method:@"GET" needToCaches:YES fetchData:^(NSData *data) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            for (NSDictionary *dic1 in dic[@"entRet"][@"lstTraint"]) {
                TrainListModel *model = [[TrainListModel alloc] init];
                [model setValuesForKeysWithDictionary:dic1];
                if ([model.type isEqualToString:@"0"]) {
                    [self.dataSource addObject:model];
                }
            }
        } updateUI:^{
            isUpdate = YES;
            [self.tableView reloadData];
        }];
    }else{
        TrainViewController *trainVC = [[TrainViewController alloc] initWithNibName:@"TrainViewController" bundle:[NSBundle mainBundle]];
        trainVC.planId = [self.dataSource[indexPath.row] planId];
        trainVC.myTitle = [self.dataSource[indexPath.row] planName];
        [self.navigationController pushViewController:trainVC animated:YES];
    }
}
@end
